/**使用自导航切换功能*/
nav_useSubChange = true;

$(() => {
    let colors = getTableNameValues('basic_info', 'color');
    let target = $("#search-color");
    for (let index in colors) {
        target.append(`<span id="nav_search-cat-${index}">${colors[index]}</span>`);
    }
});
$(() => {
    $(".sub_nav").children().each(function() {
        let t = $(this);
        (t.data("events") || {})["click"] || (this.onclick = sub_nav_click);
    })
});

function contentChange(type) {
    if (type) {
        $("#search_result>*").hide();
        $('#search_result>.t-' + type).show();
    } else {
        $("#search_result>*").show();
    }
}

let searchLog;

function updateSearchLog(val) {
    let log = localStorage.getItem('search_log') || '';
    log = new Set(log.split('\0', 30));
    log.delete('');
    if (val && typeof val === 'string') log.add(val);
    searchLog = log = [...log];
    let tar = $("#search_logs").html('');
    log.forEach((e, i) => e && $(`<span class="capsule"onclick="search(searchLog[${i}])">`).text(e).appendTo(tar));
    if (log.length > 0) tar.append(`<div onclick="localStorage.removeItem('search_log');updateSearchLog();">清空</div>`);
    else tar.append('<span style="text-align:center;display:block"><span style="margin:0 auto;">还没有搜索记录</span></span>');
    localStorage.setItem('search_log', log.join('\0'));
}
$(updateSearchLog);
async function search(v) {
    v && $("#search_input").val(v);
    v = $("#search_input").val();
    location.hash = v && 'search';
    if (v) {

        updateSearchLog(v);

        let localSearch = [];
        const M = n => {
            if (!n) return false;
            n = n.toString();
            let V = v.replace(/%/g, '');
            let index = 0;
            for (let i in V)
                if ((index = n.indexOf(V[i], index)) < 0) return false;
            return true;
        }
        Object.values(all_cats_info).forEach(e => (M(e.b) || M(e.c) || M(e.f) || M(e.l) || M(e.n) || M(e.a)) && localSearch.push({ ...e, type: 'cat' }));
        let r = await $.get(`/basic/search/${encodeURI(v)}`);
        if (r.success) {
            let tar = $("#search_result").html('');
            [...r.result, ...localSearch].forEach(e => {
                switch (e.type) {
                    case 'user':
                        {
                            $.get('/img/user?uid=' + e.uid, (r, s, x) => {
                                let type = (x.getResponseHeader('Content-Type') || "").trim().toLowerCase(),
                                    t = $(`.user-id-${e.uid} .sketch`);
                                if (type === 'text/plain') t.replaceWith(`<svg class="icon sketch"aria-hidden="true"><use xlink:href="#icon-${r}"></use></svg>`);
                                else t.attr('src', r);
                            });
                            tar.append(`<span class="module l-module infoLine t-user user-id-${e.uid}"><img class="sketch" src="https://placehold.it/256x256&text=USER"><svg class="icon mark-icon" aria-hidden="true"><use xlink:href="#icon-yonghu"></use></svg><span class="name">${e.nick||e.name}</span><span class="autograph">${e.name}</span></span>`);
                            break;
                        }
                    case 'thread':
                        {
                            e = toRealName(e);
                            tar.append(`<span class="module l-module infoLine t-thread thread-id-${e.id}"><svg class="icon sketch"style="color:#03A9F4;" aria-hidden="true"><use xlink:href="#icon-wodetiezi"></use></svg><span class="name">${e.title}</span><span class="autograph">${new Date(e.editTime).toLocaleString()}</span></span>`);
                            break;
                        }
                    case 'cat':
                        {
                            e = toRealName(e);
                            tar.append(`<span class="module l-module infoLine t-cat cat-id-${e.id}"><img class="sketch"src="/img/cat/${e.pid}" /><svg class="icon mark-icon" aria-hidden="true"><use xlink:href="#icon-paw"></use></svg><span class="name">${e.name}</span><span class="autograph">${e.nick||'喵~'}</span></span>`);
                            break;
                        }
                    case 'tag':
                        {
                            e = toRealName(e);
                            console.log(e);
                            tar.append(`<span class="module l-module infoLine t-tag tag-id-${e.id}"><svg class="icon sketch"style="color:#fdcb6e;"aria-hidden="true"><use xlink:href="#icon-biaoqiantag48"></use></svg><span class="name">${e.name}</span><span class="autograph">${new Date(e.quote).toLocaleString()}</span></span>`);
                            break;
                        }
                }
            });
        } else alert(r.err);
    }
}

$(() => search());